<?php
namespace LnkAdmin\service;

use app\admin\model\auth\Permission;
use app\admin\model\PluginModel;
use app\admin\service\MenuService;

class PluginService
{
    public function apps($state = 0)
    {
        $appObject = [];
        foreach(get_apps() as $app){
            // 判断没有plugin.json 文件
            $pluginFile = base_path($app).'plugin.json';
            
            if(is_file($pluginFile)){
                $appObject[] = json_decode(file_get_contents($pluginFile),true);

            }
        }
        return $appObject;
    }

    /**
     * 获取应用信息
     */
    public function plugin($plugin)
    {
        $pluginFile = base_path($plugin).'plugin.json';
        $info = [];
        if(is_file($pluginFile)){
            $info = json_decode(file_get_contents($pluginFile),true);

        }
        return $info;
    }

    /**
     * 安装、更新应用
     */
    public function install(String $plugin)
    {
        $pluginInfo = $this->plugin($plugin);
        $currentPluginInfo = PluginModel::where('app',$plugin)->find();
        $sqlVer = $currentPluginInfo ? $currentPluginInfo['sql_ver']:0;
        // 备份文件backups
        $this->backups($plugin);
        // 更新菜单
        $this->buildMenu($plugin);
        // 复制文件
        // 执行sql
       (new SqlService())->exceInstallSql($plugin);
       $dataSql = (new SqlService())->exceDataSql($plugin,$sqlVer);
        // 执行composer install
        // 执行npm run build
        // $this->exceBuild();
        // 保存信息到数据库
       $this->pluginSave($plugin,$dataSql[1]);
        // 完成 
       return true;

    }

    private function backups(String $plugin)
    {
        // 备份插件文件
        copy_directory(base_path($plugin),runtime_path('admin/backups'));
        // 备份数据库

    }

    /**
     * 保存信息到数据库
     */
    private function pluginSave($plugin,$sqlVer =0)
    {
        $pluginInfo = $this->plugin($plugin);
        // var_dump($pluginInfo);
        $plu =  PluginModel::where('app',$plugin)->find();
        if($plu){
            $plu->version = $pluginInfo['version'];
            $plu->sql_ver = $sqlVer;
            $plu->save();
            return $plu;
        }
        return PluginModel::create(['app'=>$plugin,'name'=>$pluginInfo['name'],'version'=>$pluginInfo['version'],'sql_ver'=>$sqlVer]);
    }


    /**
     * 执行npm run build
     */
    public function exceBuild()
    {
        TerminalService::execute(root_path('web'),'npm run build');
    }
    


    /**
     * 导入菜单
     */
    public function buildMenu($plugin)
    {
        $menuFile = base_path($plugin).'menu.php';
        $menuTree = require($menuFile);
        $menu = MenuService::buildMenuList($menuTree);
        // var_dump($menu);
        Permission::where('plugin',$plugin)->delete();
        foreach($menu as $v){
            $v['plugin'] = $plugin;
            Permission::create($v);
        }
    }
}